from typing import List, Dict, Optional
from app.config.config import Config
from app.utils.file_handler import FileHandler

class NavStructure:
    def __init__(self):
        self.file_handler = FileHandler()
        self.config = Config()
        self._ensure_data_file()
    
    def _ensure_data_file(self) -> None:
        """确保数据文件存在，如不存在则创建默认结构"""
        if not self.file_handler.read_json(self.config.NAV_STRUCTURE_FILE):
            self.file_handler.write_json(
                self.config.NAV_STRUCTURE_FILE,
                self.config.DEFAULT_NAV_STRUCTURE
            )
    
    def get_structure(self) -> List[Dict]:
        """获取导航栏结构"""
        data = self.file_handler.read_json(self.config.NAV_STRUCTURE_FILE)
        return data if data else []
    
    def save_structure(self, structure: List[Dict]) -> bool:
        """保存导航栏结构"""
        return self.file_handler.write_json(
            self.config.NAV_STRUCTURE_FILE,
            structure
        )
    
    def validate_structure(self, structure: List[Dict]) -> bool:
        """验证导航栏结构的有效性"""
        if not isinstance(structure, list):
            return False
        
        try:
            for item in structure:
                if not isinstance(item, dict):
                    return False
                if 'id' not in item or 'name' not in item:
                    return False
                if 'children' in item and not isinstance(item['children'], list):
                    return False
                if 'forms' in item and not isinstance(item['forms'], list):
                    return False
            return True
        except Exception:
            return False 